package ar.Location.Map;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.hardware.SensorListener;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import ar.Location.Constant.Define;

public class RotateView extends ViewGroup implements SensorListener {
	float mHeading = 0;
	float[] mTemp = new float[2];
	Matrix mMatrix = new Matrix();

	public RotateView(Context context, AttributeSet attSet) {
		super(context, attSet);
	}

	@Override
	protected void dispatchDraw(Canvas canvas) {

		canvas.save(Canvas.MATRIX_SAVE_FLAG);
		canvas.rotate(-mHeading, getWidth() >> 1, getHeight() >> 1);
		canvas.getMatrix().invert(mMatrix);
		super.dispatchDraw(canvas);
		canvas.restore();
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		mTemp[0] = event.getX();
		mTemp[1] = event.getY() + 400;
		mMatrix.mapPoints(mTemp);
		event.setLocation(mTemp[0], mTemp[1]);
		return super.dispatchTouchEvent(event);
	}

	public void onSensorChanged(int sensor, float[] values) {
		synchronized (this) {
			mHeading = values[0];
			invalidate();
		}
	}

	public void onAccuracyChanged(int sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		final int width = getWidth();
		final int height = getHeight();
		final int count = getChildCount();
		for (int i = 0; i < count; i++) {
			final View view = getChildAt(i);
			final int childWidth = view.getMeasuredWidth();
			final int childHeight = view.getMeasuredHeight();
			final int childLeft = (width - childWidth) / 2;
			final int childTop = (height - childHeight) / 2;
			view.layout(childLeft, childTop, childLeft + childWidth, childTop
					+ childHeight);
		}
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int w = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
		int h = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
		int sizeSpec;
		if (w > h) {
			sizeSpec = MeasureSpec.makeMeasureSpec((int) (w * Define.SQ2),
					MeasureSpec.EXACTLY);
		} else {
			sizeSpec = MeasureSpec.makeMeasureSpec((int) (h * Define.SQ2),
					MeasureSpec.EXACTLY);
		}
		final int count = getChildCount();
		for (int i = 0; i < count; i++) {
			getChildAt(i).measure(sizeSpec, sizeSpec);
		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
}
